<template>
  <el-card shadow="never" class="aui-card--fill">
    <el-form :inline="true" v-model="SearchForm"  @keydown.enter.native.prevent="getDataList()">
      <el-form-item>
        <el-input v-model="SearchForm.susername" placeholder="学生学号" clearable></el-input>
      </el-form-item>
      <el-form-item>
        <el-button @click="getDataList()">查询</el-button>
      </el-form-item>
      <el-form-item>
        <el-button  type="success" @click="approve()"
          :disabled="dataListSelections.length <= 0">批量通过</el-button>
        <el-button  type="danger" @click="reject()"
          :disabled="dataListSelections.length <= 0">批量驳回</el-button>
      </el-form-item>
    </el-form>
    <el-table :data="dataList" border v-loading="dataListLoading" @selection-change="selectionChangeHandle" style="width: 100%;">
      <el-table-column type="selection" header-align="center" align="center" width="50">
      </el-table-column>
      <!-- <el-table-column prop="id" header-align="center" align="center" label="id">
      </el-table-column> -->
        <el-table-column prop="createby" header-align="center" align="center" label="学生名字">
        </el-table-column>
      <el-table-column prop="susername" header-align="center" align="center" label="学生学号" show-overflow-tooltip>
      </el-table-column>
      <el-table-column prop="filename" header-align="center" align="center" show-overflow-tooltip width="160"  label="论文名称">
      </el-table-column>
      <el-table-column prop="advise" header-align="center" align="center" :show-overflow-tooltip="true"  width="180" label="审核意见">
      </el-table-column>
      <el-table-column prop="status" header-align="center" align="center" label="审核情况">
        <template slot-scope="scope">
          <el-tag v-if="scope.row.status === 0" size="mini" type="info">未审核</el-tag>
          <el-tag v-if="scope.row.status === 1" size="mini" type="danger">已驳回</el-tag>
          <el-tag v-if="scope.row.status === 2" size="mini" type="success">已通过</el-tag>
        </template>
      </el-table-column>
      <el-table-column fixed="right" header-align="center" align="center" width="260" label="操作">
        <template slot-scope="scope">
          <file-down :pre-view="true" icon="" api-url="/teacher/down/paper" :file-id="scope.row.id" :FileInfo="scope.row" size="mini" type="text" title="预览"></file-down>
          <file-down   icon="" api-url="/teacher/down/paper" :file-id="scope.row.id" :FileInfo="scope.row"
            size="mini" type="text" title="下载"></file-down>
          <!-- <el-button type="text" size="mini"  icon="el-icon-download" @click="download(scope.row)">下载</el-button> -->
          <el-button type="text" size="mini" @click="approve(scope.row.id)">批准通过</el-button>
          <el-button  type="text" size="mini" @click="reject(scope.row.id)">驳回修改</el-button>
        </template>
      </el-table-column>
    </el-table>
    <el-pagination @size-change="sizeChangeHandle" @current-change="currentChangeHandle" :current-page="pageIndex"
      :page-sizes="[10, 20, 50, 100]" :page-size="pageSize" :total="totalPage"
      layout="total, sizes, prev, pager, next, jumper">
    </el-pagination>
  </el-card>
</template>

<script>
import FileDown from '@/components/FileDown.vue';
import servicesApi from '@/services/servicesApi';
import debounce from 'lodash/debounce';
export default {
    data() {
        return {
            SearchForm: {
                susername: ''
            },
            dataList: [
                {
                    id: '',
                    susername: '',
                    createby: '',
                    filename: '',
                    advise: '',
                    status: 0
                }
            ],
            pageIndex: 1,
            pageSize: 10,
            totalPage: 0,
            dataListLoading: false,
            dataListSelections: [],
            deleteList: []
        };
    },
    activated() {
        this.getDataList();
    },
    created() {
        this.getDataList();
    },
    methods: {
        // 获取数据列表
        getDataList: debounce(function() {
            this.dataListLoading = true;
            let pageInfo = {
                current: this.pageIndex,
                size: this.pageSize,
                name: this.SearchForm.susername
            };
            servicesApi.postpaperApi(pageInfo).then(res => {
                // console.log(res.data)
                let code = res.data.code;
                let data = res.data.data;
                if (code === 200) {
                    this.dataList = data.list;
                    this.totalPage = data.total;
                }
                else {
                    this.dataList = [];
                    this.totalPage = 0;
                }
                this.dataListLoading = false;
            });
        }, 1000, { 'leading': true, 'trailing': false }),
        // 每页数
        sizeChangeHandle(val) {
            this.pageSize = val;
            this.pageIndex = 1;
            this.getDataList();
        },
        // 当前页
        currentChangeHandle(val) {
            this.pageIndex = val;
            this.getDataList();
        },
        // 多选
        selectionChangeHandle(val) {
            this.dataListSelections = val;
            // console.log('多选')
            // console.log(this.dataListSelections)
        },
        //批准通过
        approve(id) {
            let userIds = id ? [id] : this.dataListSelections.map(item => {
                return item.id;
            });
            // console.log(userIds)
            this.$prompt('请输入通过意见', {
                confirmButtonText: '确定',
                cancelButtonText: '取消'
            })
                .then(({ value }) => {
                // console.log(value)
                this.deleteList = userIds;
                let checkList = {
                    advise: value,
                    list: this.deleteList,
                    status: 2
                };
                servicesApi.checkpaperApi(checkList).then(res => {
                    // console.log(res.data)
                    let code = res.data.code;
                    if (code === 200) {
                        this.$message({
                            type: 'success',
                            message: '批准通过成功',
                            duration: 1500,
                            onClose: () => {
                                this.getDataList();
                            }
                        });
                    }
                    else {
                        this.$message.error(res.data.msg);
                    }
                });
            }).catch(() => {
                this.$message({
                    type: 'warning',
                    message: '取消批准通过'
                });
            });
        },
        //驳回
        reject(id) {
            let userIds = id ? [id] : this.dataListSelections.map(item => {
                return item.id;
            });
            // console.log(userIds)
            this.$prompt('请输入驳回意见', {
                confirmButtonText: '确定',
                cancelButtonText: '取消'
            })
                .then(({ value }) => {
                // console.log(value)
                this.deleteList = userIds;
                let checkList = {
                    advise: value,
                    list: this.deleteList,
                    status: 1
                };
                servicesApi.checkpaperApi(checkList).then(res => {
                    // console.log(res.data)
                    let code = res.data.code;
                    if (code === 200) {
                        this.$message({
                            type: 'success',
                            message: '驳回成功',
                            duration: 1500,
                            onClose: () => {
                                this.getDataList();
                            }
                        });
                    }
                    else {
                        this.$message.error(res.data.msg);
                    }
                });
            }).catch(() => {
                this.$message({
                    type: 'info',
                    message: '取消驳回'
                });
            });
        },
        //下载文件
        download: debounce(function(row) {
            this.percentage = 0;
            this.percentage = 25;
            // console.log(row)
            let Form = {
                filename: 'xss攻击与防御总结',
                path: 'student/paper',
                suffix: 'docx'
            };
            let FileName = 'xss攻击与防御总结.docx';
            if (row) {
                Form.filename = row.filename;
                Form.path = row.path;
                Form.suffix = row.suffix;
                FileName = Form.filename + '.' + Form.suffix;
            }
            //进度条恢复为 0 
            this.percentage = 50;
            //按钮置灰 不可点击
            this.isDisabled = true;
            servicesApi.downloadFiles(Form).then(res => {
                this.percentage = 75;
                // console.log(res)
                //xml返回数据的钩子函数，可以用来获取数据的进度 具体可查看axios的官网
                //     onDownloadProgress: (progressEvent) => {
                //         //progressEvent.loaded 下载文件的当前大小
                //         //progressEvent.total  下载文件的总大小 如果后端没有返回 请让他加上！
                //         let progressBar = Math.round(progressEvent.loaded / progressEvent.total * 100);
                //         //接收进度为99%的时候需要留一点前端编译的时间
                //         if (progressBar >= 99) {
                this.percentage = 99;
                this.title = '下载完成，文件正在编译。';
                //         } else {
                //             this.percentage = progressBar;
                //             this.title = '正在下载，请稍等。';
                //         }
                //     }
                try {
                    const blob = new Blob([res.data], {
                        type: 'application/octet-stream'
                    });
                    const downloadElement = document.createElement('a');
                    // 创建下载的链接
                    // 兼容不同浏览器的URL对象
                    const url = window.URL || window.webkitURL || window.moxURL;
                    const href = url.createObjectURL(blob);
                    downloadElement.href = href;
                    // 下载后文件名
                    downloadElement.download = FileName;
                    document.body.appendChild(downloadElement);
                    // 点击下载
                    downloadElement.click();
                    // 下载完成移除元素
                    document.body.removeChild(downloadElement);
                    // 释放掉blob对象
                    url.revokeObjectURL(href);
                    //编译文件完成后，进度条展示为100
                    this.percentage = 100;
                    //下载完成 可以重新点击按钮下载
                    this.isDisabled = false;
                }
                catch (error) {
                    // console.log('下载的文件出错', error)
                }
            }).catch(error => {
                // console.log('下载的文件出错', error)
            });
        }, 1000, { 'leading': true, 'trailing': false }),
    },
    components: { FileDown }
}
</script>
